package com.ucar.umock.client.config;

import com.ucar.umock.client.UMockHelper;
import com.ucar.umock.client.annotation.UMock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * @ClassName UMockConfigParser
 * @Description TODO
 * @Author zhanbs baoshan.zhan@ucarinc.com
 * @Date 2020/4/2 15:35
 * @Version 1.0
 **/
@Slf4j
public class UMockMethodConfigParser {


    private void parseUMockMethod(Class clazz,UMock mockClassAnn){
        Method[] methods=clazz.getMethods();
        for(Method method:methods){
            UMock mockMethodAnn=method.getAnnotation(UMock.class);
            if(mockMethodAnn!=null){
                UMockMethodConfigBean meta=UMockMethodConfigBean
                        .builder()
                        .key(UMockHelper.getMockMethodConfigKey(method))
                        .classMockName(mockClassAnn.name())
                        .className(clazz.getName())
                        .methodName(method.getName())
                        .methodMockName(mockMethodAnn.name())
                        .fixedValue(mockMethodAnn.fixedValue())
                        .fixedArray(mockMethodAnn.fixedArray())
                        .handleType(mockMethodAnn.handleType())
                        .customHandle(mockMethodAnn.customHandle())
                        .build();
                UMockHelper.getMockMethodConfigOperate().putMockMethodConfig(meta);
            }
        }
    }


    public void parse(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        String [] beanNames=configurableListableBeanFactory.getBeanDefinitionNames();
        log.info("bean count="+beanNames.length);
        for(String beanName:beanNames){
            BeanDefinition beanDefinition=configurableListableBeanFactory.getBeanDefinition(beanName);
            Class clazz= null;
            try {
                if(beanDefinition.getBeanClassName()!=null){
                    clazz = Class.forName(beanDefinition.getBeanClassName());
                    Annotation mockClassAnn=clazz.getAnnotation(UMock.class);
                    if(mockClassAnn!=null){
                        this.parseUMockMethod(clazz,(UMock)mockClassAnn);
                    }
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

        }
    }


}
